package Comprehensive_03;

import java.util.*;

/*
  测试类
 */
public class Demo8 {
    public static void main(String[] args) {
        //1.创建Scanner对象
        Scanner sc = new Scanner(System.in);
        //2.创建Map集合对象
        HashMap<Product, Integer> hashMap = new HashMap<>();
        //3.循环将商品加入购物车
        while (true) {
            System.out.println("请你输入要添加商品的店铺:");
            String store = sc.next();
            if (store.equals("end")) {
                break;
            }else{
                System.out.println("请你要输入添加的商品名称:");
                String name = sc.next();
                //4.根据输入的店铺名称和商品名称,封装成Product对象
                Product product = new Product(store, name);
                if (!hashMap.containsKey(product)) {
                    //5.如果集合中不包含我们添加的同一个店铺同一个商品的话,直接往集合中添加该商品
                    hashMap.put(product, 1);
                    look(hashMap);
                } else {
                    //6.否则将该商品对应的值(数量)从集合中获取出来,让其加1
                    Integer number = hashMap.get(product);
                    number++;
                    //7.将加1之后的商品重新添加到集合中
                    hashMap.put(product, number);
                    look(hashMap);
                }
            }
        }
    }

    public static void look(HashMap<Product, Integer> hashMap) {
        //8.遍历集合
        Set<Map.Entry<Product, Integer>> entrySet = hashMap.entrySet();
        for (Map.Entry<Product, Integer> entry : entrySet) {
            Product key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key+"-->"+value);
        }
    }


}
//商品类
class Product {
    //店铺名称
    private String store;
    //商品名称
    private String name;

    public Product(String store, String name) {
        this.store = store;
        this.name = name;
    }

    public String getStore() {
        return store;
    }

    public void setStore(String store) {
        this.store = store;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return Objects.equals(store, product.store) &&
                Objects.equals(name, product.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(store, name);
    }

    @Override
    public String toString() {
        return "Product{" +
                "store='" + store + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}